// 01wasteRecovery/wasteRecovery.js
var co = require('../resource/js/common.js')
var ws = require('../resource/js/websocket.js')
var app = getApp()
var _this, _data, _opt
Page({

   /**
    * 页面的初始数据
    */
   data: {
      rubbishType: '',
      typePop: false, //个人或企业弹出
      selectPop: false, //分类弹出
      BroadcastImgsList: '',
      bizList: '', //企业列表
      bizPop: false, //企业；列表弹出
      rubbishTypeArr: [],
      userType: '', //下单人类型
      audioSrc: '',//语音地址
      wasteImg:[],//图片地址
      playOk:true,//
      personalAddress: [], //用户地址列表
      hint: true,   
      showType:null,  
      typeValue:null, 
   },
   /**
    * 生命周期函数--监听页面加载
    */
   onLoad: function(opt) {
      _this = this
      _data = this.data
      app.Data.userInfo = wx.getStorageSync('userInfo'),
         this.rubType()
      this.getBroadcast()
      if (!co.empty(app.Data.userInfo)) {
         //this.initWS_Login()
         var _Room_ID = 'jyhs_user';
         //ws.bindSocketListener(app.Data.userInfo, _Room_ID, _this.onSocketMsg)
         ws.initWebsocket(app.Data.userInfo, _Room_ID, function(res) {
            console.log('【wss初始化及登录结果】', res)
         })
         ws.onSocketMsg(_this.onSocketMsg)
      }
      console.log('app.Data1==', app.Data)
   },
   //获取用户地址
   getPersonalAddress: function () {
      var userInfo = app.Data.userInfo
      var url = 'address/Addrmg/address'
      var param = {
         User_ID: userInfo.User_ID
      }
      co.getShareApi(url, param, function (res) {
         if (res.code == 0) {
            _this.setData({
               personalAddress: res.data,
               hint: false
            })
         } 
      })
   },
   //跳转至收货地址页面
   goToAddressPage() {
      wx.navigateTo({
         url: '/04myCenter/03receiveAddress/03receiverAddress?reload='+1,
      })
   },
   //获取垃圾type
   rubType: function() {
      var url = 'goods/Goods/getGoodsCate'
      co.getJyhsApi(url, '', function(res) {

         if (res.code == 0) {
            _this.setData({
               rubbishType: res.data
            })
         } else {
            co.toastAllText(res.msg)
         }
      })
   },
   //一键旧约回收
   rubRecovery: function(e) {
      if (!app.Data.userInfo) {
         _this.closePop()
         co.toastAllText('请先登录')
         wx.switchTab({
            url: '/04myCenter/myCenter',
         })
         return
      }
      var userInfo = app.Data.userInfo
      //var type = e.currentTarget.dataset.type
      var arr = _data.rubbishTypeArr
      var type = arr.join()
      //console.log('e', e)
      console.log('type', type)
      console.log('app.Data===2', app.Data)

      var url = 'order/Order/makeOrder'
      if (_data.userType == 'enterprise') {
         var param = {
            
            Biz_ID: app.Data.shopInfo.Biz_ID,
            Goods_Cate: type
         }
      } else if (_data.userType == 'personal') {
         var param = {
            User_ID: userInfo.User_ID,
            Goods_Cate: type
         }
      } else if (_data.userType == '') {
         console.log("_data.typeValue.currentTarget.dataset.type", _data.typeValue.currentTarget.dataset.type)
         var type1 = _data.typeValue.currentTarget.dataset.type
         var type2 = e.currentTarget.dataset.type
         if (co.empty(type1)){
            var param = {
               User_ID: userInfo.User_ID,
               Goods_Cate: type2
            }
         }else{
            var param = {
               User_ID: userInfo.User_ID,
               Goods_Cate: type1
            }
         }
      }
      param.Goods_Image = _data.wasteImg[0]
      co.getJyhsApi(url, param, function(res) {
         console.log('res===', res)
         if (res.code == 0) {
            //app.Data.shopInfo.Reclaim_User_ID
            _this.setData({
               rubbishTypeArr:[]
            })
            co.toastAllText(res.msg)
            _this.closePop() //关闭弹窗

            if (res.data.Is_Biz_Order == 0) {
               _this.ws_send_user(res.data.Reclaim_User_ID) //用户下单成功发送websocket
               var orderID = res.data.Order_ID
               wx.navigateTo({
                  url: '/04myCenter/04wasteOrder/02wasteOrderDetail/wasteOrderDetail?orderID=' + orderID,
               })


            } else if (res.data.Is_Biz_Order == 1) {
               _this.ws_send_order(res.data.Reclaim_User_ID, app.Data.shopInfo.Biz_ID) //企业下单成功发送websocket
               _data.userType = '' //企业下单成功，下单类型设置为空
               var orderID = res.data.Order_ID
               wx.navigateTo({
                  url: '/04myCenter/04wasteOrder/02wasteOrderDetail/wasteOrderDetail?orderID=' + orderID,
               })


            }
         } else if (res.code == 29300) {
            if (res.data == 'no_address') {
               co.confirm(res.msg, '', '前往设置', function(res) {
                  if (res) {
                     wx.navigateTo({
                        url: '/04myCenter/03receiveAddress/03receiverAddress',
                     })
                  }
               })
            } else if (res.data == 'no_complete_order') {
               co.toastAllText(res.msg)
               _this.closePop()
            }
         } else {
            co.toastAllText(res.msg)
         }
      })
   },
   //选中回收类型
   checkboxChange: function(e) {
      var type = e.detail.value
      this.setData({
         rubbishTypeArr: type
      })
   },
   //一键就约回收按钮弹出
   quickPop: function() {
      this.setData({
         typePop: true
      })
   },
   //关闭弹出
   closePop: function() {
      this.setData({
         typePop: false,
         selectPop: false,
         bizPop: false,
         wasteImg:[]
      })
   },
   //个人下单
   typeSelectPop: function(e) {
      var userType = e.currentTarget.dataset.type
      _this.closePop()
      if (userType == 'personal') {
         this.setData({
            selectPop: true,
            userType: userType,
            showType:true
         })
      } else if (userType == 'enterprise') {
         this.setData({
            userType: userType
         })
         _this.bizSelectPop()
      }
   },
   //获取轮播图
   getBroadcast: function() {
      var url = 'jyhs/Admin/getBizInfo'
      co.getShareApi(url, {
         field: "Broadcast_Imgs"
      }, function(res) {
         //console.log('res===x=', res.data)
         if (res.code == 0) {
            _this.setData({
               BroadcastImgsList: res.data.Broadcast_Imgs
            })
         } else {

         }
      })
   },
   //企业列表
   bizSelectPop: function() {
      if (!app.Data.userInfo) {
         wx.switchTab({
            url: '/04myCenter/myCenter',
         })
      }
      var userInfo = app.Data.userInfo
      // var url = 'jyhs/Usermg/autoLogin'
      // console.log('app.Data',app.Data)
      // var param = {
      //    unionid: userInfo.unionid
      // }
      var url = 'jyhs/Admin/getBizList'
      var param = {
         User_ID: userInfo.User_ID
      }
      if (userInfo == ''){
         co.toastAllText("请先登录")
      }else{
         co.getShareApi(url, param, function (res) {
            if (res.code == 0) {
               console.log('res===1', res)
               _this.closePop()
               _this.setData({
                  bizList: res.data,
                  bizPop: true
               })
               //只有一家企业的时候
               if (res.data.length == 1) {
                  _this.gotoShop(res.data[0])
               }
            } else {
               co.toastAllText(res.msg)
            }
         })
      }
      
   },
   // 选择企业
   intoShop: function(e) {
      var id = e.currentTarget.id
      //console.log('e',e)
      //保存选择店铺的下标，下次默认登录这个ID
      wx.setStorageSync('shopIndex', id)
      this.gotoShop(this.data.bizList[id])
   },
   //进入企业
   gotoShop: function(shopInfo) {
      app.Data.shopInfo = shopInfo
      console.log("【获取商家信息shopInfo】===", shopInfo)
      _this.closePop()
      this.setData({
         selectPop: true,
         showType:true
      })
      // if (shopInfo.Biz_Type == 'p_org' || shopInfo.Biz_Type == 'amtf') {
      //    var url = '/293admin/00center/home'
      //    url += '?Biz_ID=' + shopInfo.Biz_ID
      //    wx.navigateTo({
      //       url: url,
      //    })
      // } else {
      //    app.switchTabHome()
      // }
   },
   toRubRecovery: function(e) {
      // co.confirm('确定下单吗', '取消', '确定', function(res) {
      //    if (res) {
      //       _this.rubRecovery(e)
      //    }
      // })
      _data.typeValue = e
      _this.setData({
         selectPop: true,
         showType: false
      })
   },
   //获取语音
   getVoice: function(message, type) {
      co.getJyhsApi('api/Voice/voiceRecognite', {
         vol: 5,
         message: message, //企业订单
         type: type
      }, function(res) {

         _this.setData({
            audioSrc: res.data
         })
         setTimeout(function() {
            _this.nowPlay()
         }, 100)
      })
   },
   //初始化WS,并登录用户
   // initWS_Login() {
   //    var _Room_ID = 'jyhs_user';
   //    ws.initWebsocket(app.Data.userInfo, _Room_ID, function (res) {
   //       console.log('【wss初始化及登录结果】', res)
   //    })
   //    ws.onSocketMsg(function (res) {
   //       console.log('first【foodInfo页面监听到】', res)
   //       if (res.type == 'getBizOrder_Notify'){
   //          var message = '你的订单已被接'
   //          console.log('1====',app.Data)
   //          if(res.to_biz_id == app.Data.shopInfo.Biz_ID){
   //             _this.getVoice(message,3)
   //          }
   //       } else if (res.type == 'getUserOrder_Notify'){
   //          var message = '你的订单已被接'
   //          console.log('2====', app.Data)
   //          if (res.to_user_id == app.Data.userInfo.User_ID) {
   //             _this.getVoice(message,3)
   //          }
   //       } 
   //       else if (res.type == 'payOrder'){
   //          var message = '你的订单已被支付'
   //          console.log('3====', app.Data)
   //          if (res.to_user_id == app.Data.userInfo.User_ID) {
   //             _this.getVoice(message,5)
   //          }
   //       }
   //    })
   // }, 

   onSocketMsg: function(res) {
      console.log('first【wasteRecovery页面监听到】', res)
      if (res.type == 'getBizOrder_Notify') {
         var message = '你的订单已被接'
         console.log('1====', app.Data)
         if (res.to_biz_id == app.Data.shopInfo.Biz_ID) {
            _this.getVoice(message, 3)
         }
      } else if (res.type == 'getUserOrder_Notify') {
         var message = '你的订单已被接'
         console.log('2====', app.Data)
         if (res.to_user_id == app.Data.userInfo.User_ID) {
            _this.getVoice(message, 3)
         }
      } else if (res.type == 'payOrder') {
         var message = '你的订单已被支付'
         if (res.to_biz_id) {
            if (res.to_biz_id == app.Data.shopInfo.Biz_ID) {
               _this.getVoice(message, 5)
            }
         } else {
            if (res.to_user_id == app.Data.userInfo.User_ID) {
               _this.getVoice(message, 5)
            }
         }

         //console.log('3====', app.Data)

      }
   },

   //企业下单发送web
   ws_send_order: function(Reclaim_User_ID, biz_id) {
      var msg = {
         type: 'getBizOrder',
         reclaim_id: Reclaim_User_ID,
         from_biz_id: biz_id
      }
      console.log('ws_send_order msg=====', msg)
      ws.sendSocketMsg(JSON.stringify(msg), function(res) {
         console.log('【sendSocketMsg:发送成功回调（222）】')
      })
   },
   //用户下单发送web
   ws_send_user: function(Reclaim_User_ID) {
      var msg = {
         type: 'getUserOrder',
         reclaim_id: Reclaim_User_ID,
         from_user_id: app.Data.userInfo.User_ID
      }
      console.log('ws_send_order msg=====', msg)
      ws.sendSocketMsg(JSON.stringify(msg), function(res) {
         console.log('【sendSocketMsg:发送成功回调（333）】')
      })
   },
   nowPlay: function(res) {
      this.audioCtx.play()
      console.log("【播放】")
   },

   /**
    * 生命周期函数--监听页面初次渲染完成
    */
   onReady: function() {
      this.audioCtx = wx.createAudioContext('myAudio')
   },

   /**
    * 生命周期函数--监听页面显示
    */
   onShow: function() {
      _this.getPersonalAddress()
      // if (app.Data.userInfo && !ws.isInitialized()) {
      //    var _Room_ID = 'jyhs_user';
      //    ws.bindSocketListener(app.Data.userInfo, _Room_ID, _this.onSocketMsg)
      // }
      if(app.Data.userInfo) {
         ws.onSocketMsg(_this.onSocketMsg)
      }
   },
   //选择内景图片
   chooseImage: function (e) {
      wx.chooseImage({
         count: 1, // 最多可以选择的图片张数，默认9
         sizeType: ['compressed'], // original 原图，compressed 压缩图，默认二者都有
         sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有 
         success(res) {
            console.log("【获取图片路径】===", res)
            //上传内景图
            _this.uploadimg(res.tempFilePaths[0])
         },
      })
   },
   //上传
   uploadimg: function (img) {
      wx.showLoading({
         title: '图片上传中',
      })
      //console.log("img", img)
      //console.log("_data.shopInfo.Biz_ID", _data.shopInfo.Biz_ID)
      wx.uploadFile({
         url: 'https://api.jyhs.ls293.cn/api/Upload/img',
         filePath: img,
         name: 'image',
         formData: {
            dir: 'order_call'
         },
         success: function (res) {
           //console.log('res2==',res)
            var obj = JSON.parse(res.data)
            //console.log("obj====", obj)
            var wastePic = []
            wastePic.push(obj.data.wwwPath)
            //console.log('wastePic',wastePic)
            _this.setData({
               wasteImg:wastePic
            })
            // console.lo()
            // console.log('wsat')
            console.log('wasteImg', _data.wasteImg)
            wx.hideLoading()
         },
         fail: function (res) {
            wx.hideLoading()
            console.log('上传内景图失败res=====', res)

         },
      })
   },
   //垃圾图片删除
   deleteCarouselImage: function (e) {
      var list = _data.wasteImg
      console.log('list',list)
      var index = e.currentTarget.id
      console.log('index',index)
      //切割点击的图片路径删除该图片
      var delImage = list[index].replace('http://h5.jyhs.ls293.cn', '')
      //var delImage = delImage.replace('_160x160.png', '')
      //移除显示的图片
      list.splice(index, 1)
      co.getJyhsApi('api/Upload/deleteImg', {
         imageFile: delImage
      }, function (res) {
         co.toastAllText(res.msg)
         if (res.code == 0) {
            //保存商家信息
            _this.setData({
               wasteImg:list
            })           
               wx.hideLoading()            
         }
      })
   },
   //视频播放
   videoPlay:function(){
      this.setData({
         playOk:false
      })
   },
})